<template>
  <div class="login-container">
    <div class="login-image">
      <div class="brand">
        <div class="brand-icon">
          <i class="fas fa-tshirt"></i>
        </div>
        <span class="brand-name">StyleFit</span>
      </div>
      <div class="image-text">
        <h2>探索你的个性时尚</h2>
        <p>加入StyleFit，让AI为你打造完美穿搭，展现独特魅力。</p>
      </div>
    </div>

    <div class="login-form">
      <div class="form-header">
        <h2>欢迎回来</h2>
        <p>请登录您的账号以继续使用</p>
      </div>

      <a-form
        ref="formRef"
        :model="formState"
        name="login"
        @finish="handleLogin"
        layout="vertical"
        class="login-form-content"
      >
        <a-form-item
          name="email"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' }
          ]"
        >
          <a-input
            v-model:value="formState.email"
            placeholder="邮箱"
            size="large"
          >
            <template #prefix>
              <i class="fas fa-envelope"></i>
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          name="password"
          :rules="[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码至少6个字符' }
          ]"
        >
          <a-input-password
            v-model:value="formState.password"
            placeholder="密码"
            size="large"
          >
            <template #prefix>
              <i class="fas fa-lock"></i>
            </template>
          </a-input-password>
        </a-form-item>

        <div class="form-options">
          <a-checkbox v-model:checked="formState.remember">记住我</a-checkbox>
        </div>

        <a-button
          type="primary"
          html-type="submit"
          size="large"
          block
          class="login-button"
          :loading="loading"
        >
          {{ loading ? '登录中...' : '登录' }}
        </a-button>

        <div class="register-link">
          还没有账号？<router-link to="/register">立即注册</router-link>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { message } from 'ant-design-vue'
import '@/assets/styles/auth.css'

export default defineComponent({
  name: 'LoginPage',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const formRef = ref(null)
    
    const formState = reactive({
      email: '',
      password: '',
      remember: false
    })

    const handleLogin = async () => {
      try {
        console.log('表单数据:', formState)
        console.log('表单引用:', formRef.value)
        
        // 验证表单
        if (!formRef.value) {
          console.error('表单引用不存在')
          return
        }
        
        try {
          await formRef.value.validate()
        } catch (error) {
          console.error('表单验证错误:', error)
          return
        }
        
        // 设置加载状态
        loading.value = true
        
        console.log('开始登录请求...')
        console.log('请求URL:', '/api/login')
        console.log('请求数据:', {
          email: formState.email,
          passwordHash: formState.password
        })

        const response = await axios.post('/api/login', {
          email: formState.email,
          passwordHash: formState.password
        })

        console.log('登录响应:', response)

        if (response.data.success) {
          const token = response.data.data
          localStorage.setItem('token', token)
          
          // 使用token获取用户信息
          console.log('获取用户信息...')
          const userResponse = await axios.get(`/api/users/email/${formState.email}`, {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            }
          })
          
          console.log('用户信息响应:', userResponse)
          
          if (userResponse.data.success) {
            const userData = userResponse.data.data
            localStorage.setItem('userId', userData.user_id)
            localStorage.setItem('username', userData.username)
            localStorage.setItem('email', userData.email)
            
            // 如果选择了记住我，保存邮箱
            if (formState.remember) {
              localStorage.setItem('rememberedEmail', formState.email)
            } else {
              localStorage.removeItem('rememberedEmail')
            }
            
            message.success('登录成功')
            router.push('/')
          } else {
            message.error('获取用户信息失败')
          }
        } else {
          message.error(response.data.errorMsg || '登录失败')
        }
      } catch (error) {
        console.error('Login error:', error)
        if (error.response) {
          message.error(error.response.data.errorMsg || '登录失败，请重试')
        } else {
          message.error('网络错误，请检查网络连接')
        }
      } finally {
        // 无论成功失败，都关闭加载状态
        loading.value = false
      }
    }

    const initForm = () => {
      const savedEmail = localStorage.getItem('email')
      if (savedEmail) {
        formState.email = savedEmail
        formState.remember = true
      }
    }

    onMounted(() => {
      initForm()
    })

    return {
      formRef,
      formState,
      loading,
      handleLogin
    }
  }
})
</script>


